<template>
  <div class="content_body">
    <div class="pageTitle">
      页面管理
    </div>
    <div class="page_body">
      <div class="tool">
        <el-row :gutter="24">
          <el-col :xs="16" :sm="12" :md="8" :lg="6" :xl="4">
            <el-button
              size="small"
              icon="el-icon-search"
              v-on:click="addPage()"
              class="my_btn"
              >新增</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-table :data="treeTableData" row-key="pageId"  :tree-props="{children: 'children', hasChildren: 'hasChildren'}" style="width: 100%" v-loading="loading">
        <el-table-column prop="pageName" label="页面名" min-width="10%">
        </el-table-column>
        <el-table-column prop="typeName" label="页面类型" min-width="10%">
        </el-table-column>
        <el-table-column prop="pagePath" label="页面路径" min-width="10%">
        </el-table-column>
        <el-table-column prop="parentName" label="父页面" min-width="10%">
        </el-table-column>
        <el-table-column prop="redirect" label="重定向" min-width="10%">
        </el-table-column>
        <el-table-column prop="component.componentName" label="组件名" min-width="10%">
        </el-table-column>
        <el-table-column prop="pageIcon" label="图标名" min-width="10%">
        </el-table-column>
        <el-table-column prop="bgColor" label="图标背景" min-width="10%">
        </el-table-column>
        <el-table-column prop="isLogin" label="登录访问" min-width="5%">
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="15%">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="changePage(scope.$index, tableData)"
              type="primary"
              icon="el-icon-edit"
              circle
              size="small"
            >
            </el-button>
            <el-button
              @click.native.prevent="deletePage(scope.$index, tableData)"
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="isAddPage?'添加页面':'修改页面'" :visible.sync="dialogFormVisible" >
      <el-form :model="dialogPageForm" :rules="rules" ref="dialogPageForm">
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="页面名"
              :label-width="formLabelWidth"
              prop="pageName"
            >
              <el-input
                size="small"
                v-model="dialogPageForm.pageName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="页面类型"
              :label-width="formLabelWidth"
              prop="typeName"
            >
              <el-select :disabled="pageSelect"  size="small" v-model="dialogPageForm.typeName" placeholder="请选择页面类型">
                <el-option label="根目录" value="根目录"></el-option>
                <el-option label="一级目录" value="一级目录"></el-option>
                <el-option label="二级目录" value="二级目录"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="页面路径"
              :label-width="formLabelWidth"
              prop="pagePath"
            >
              <el-input
                size="small"
                v-model="dialogPageForm.pagePath"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="父页面"
              :label-width="formLabelWidth"
              prop="email"
            >
              <el-select  :disabled="parentSelect"  size="small" v-model="dialogPageForm.parentId" placeholder="请选择父级页面">
                <el-option  label=""  value=""></el-option>
                <el-option v-for="item in dialogPageForm.parentList" :label="item.pageName" :key="item.pageId" :value="item.pageId"></el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="重定向路径"
              :label-width="formLabelWidth"
              prop="redirect"
            >
              <el-input
                size="small"
                v-model="dialogPageForm.redirect"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="组件名"
              :label-width="formLabelWidth"
              prop="component"
            >
               <el-select :loading="selectLoading"  size="small" filterable  v-model="dialogPageForm.componentId" placeholder="请选择组件">
                 <el-option  label=""  value=""></el-option>
                <el-option  v-for="item in dialogPageForm.componentList" :label="item.componentName" :key="item.componentId" :value="item.componentId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="12">
            <el-form-item
              label="图标名"
              :label-width="formLabelWidth"
              prop="pageIcon"
            >
              <el-input
                size="small"
                v-model="dialogPageForm.pageIcon"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="图标背景"
              :label-width="formLabelWidth"
              prop="bgColor"
            >
              <el-input
                size="small"
                v-model="dialogPageForm.bgColor"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item  label="登录访问" :label-width="formLabelWidth">
              <el-switch v-model="dialogPageForm.isLogin"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="my_btn"
          size="small"
          @click="dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button
          class="my_btn"
          size="small"
          type="primary"
          @click="submitPageForm('dialogPageForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getAllPage, deletePage ,addPage,changePage,getAllComponent} from "@/api/api";
export default {
  name: "page",
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      keyWord: "",
      loading: false,
      tableData: [],
      treeTableData:[],
      dialogFormVisible: false,
      parentSelect:false,
      pageSelect:false,
      formLabelWidth: "120px",
      isAddPage:false,
      selectLoading:false,
      dialogPageForm: {
        pageId:"",
        pageName: "",
        pageType: "",
        typeName:"",
        pagePath: "",
        pageIcon: "",
        parentId:"",
        parentName:"",
        bgColor:"",
        redirect:"",
        pageTitle:"",
        componentId:"",
        componentName:"",
        isLogin:"",
        parentList:[],
        componentList:[]
      },
      rules: {
        pageName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  mounted: function() {
    this.getData();
  },
  watch:{
     'dialogPageForm.typeName':function(newValue){
        switch(newValue){
          case "根目录":
            this.dialogPageForm.parentList=[]
            break
          case "一级目录":
            this.dialogPageForm.parentList=this.tableData.filter((item)=>{
              return item.typeName=="根目录"?true : false;
            })
            break
          case "二级目录":
            this.dialogPageForm.parentList=this.tableData.filter((item)=>{
              return item.typeName=="一级目录"?true :false;
            })
          }
     }
  },
  computed:{
  },
  methods: {
    //请求数据
     async getData() {
      this.loading = true;
      let data = await getAllPage(null);
      console.log(data);
      this.tableData = data.data.list.map((item, index) => {
        //计算数据序号，并添加到数组中
        item.order = (this.pageNum - 1) * this.pageSize + index + 1;
        item.isLogin = item.isLogin == 0 ? "启用" : "禁用";
        let array=(data.data.list.filter(index=>{
          if(index.pageId==item.parentId){
            return true
          }else{
            return false
          }
        }))
        item.parentName=array.length!=0?array[0].pageName:"无"
        return item;
      });
      this.treeTableData=this.getTreeTableData(this.tableData);
      console.log(this.treeTableData)
      this.total = data.data.total;
      this.loading = false;
    },
    getTreeTableData(tbData){
      return tbData.reduce(function sortTree(prev,current,index,array){
          let cArray=[...array]
          cArray.splice(index,1)
          if(current.typeName=="根目录"&&prev[0]=="根目录"){
              let returnData=cArray.length==0?[]:cArray.reduce(sortTree,["一级目录",current.pageId])
              returnData==undefined||returnData.length==0?"":(current.children=returnData)
              prev.push(current)
          }else if(current.typeName=="一级目录"&&prev[0]=="一级目录"&&current.parentId==prev[1]){
              let returnData=cArray.length==0?[]:cArray.reduce(sortTree,['二级目录',current.pageId])
              returnData.length==0?"":(current.children=returnData)
              prev.push(current)
          }else if(current.typeName=="二级目录"&&prev[0]=="二级目录"&&current.parentId==prev[1]){
              let returnData=cArray.length==0?[]:cArray.reduce(sortTree,["三级目录",current.pageId])
              returnData.length==0?"":(current.children=returnData)
              prev.push(current)
          }
          if(index>=array.length-1){
            prev.splice(0,2)
          }
          return prev
       },['根目录',''])
    },
    //添加用户按钮触发事件
    addPage() {
      this.clearDialogPageForm()
      this.pageSelect=false
      this.pageSelect=false
      this.dialogFormVisible = true;
      this.loadComponentList()
      this.isAddPage=true;
    },
    //修改按钮触发事件
    changePage(index, rows){
      this.clearDialogPageForm()
      this.parentSelect=this.tableData.filter(item=>{
        if(item.parentId==rows[index].pageId){
          return true
        }else{
          return false
        }
      }).length!=0
      this.pageSelect=true
      this.dialogFormVisible = true;
      this.loadComponentList()
      this.isAddPage=false;
      this.dialogPageForm={...rows[index]}
      // this.dialogPageForm.pageId=rows[index].pageId
      // this.dialogPageForm.pageName=rows[index].pageName
      // this.dialogPageForm.pageType=rows[index].pageType
      // this.dialogPageForm.typeName=rows[index].typeName
      // this.dialogPageForm.pagePath=rows[index].pagePath
      // this.dialogPageForm.pageIcon=rows[index].pageIcon
      // this.dialogPageForm.parentId=rows[index].parentId
      // this.dialogPageForm.parentName=rows[index].parentName
      // this.dialogPageForm.bgColor=rows[index].bgColor
      // this.dialogPageForm.redirect=rows[index].redirect
      // this.dialogPageForm.pageTitle=rows[index].pageTitle
      // this.dialogPageForm.component=rows[index].component
      // this.dialogPageForm.isLogin=rows[index].isLogin
    },
    //清空弹窗内容方法
    clearDialogPageForm(){
        this.dialogPageForm.pageId=''
        this.dialogPageForm.pageName=''
        this.dialogPageForm.pageType=''
        this.dialogPageForm.typeName=''
        this.dialogPageForm.pagePath=''
        this.dialogPageForm.pageIcon=''
        this.dialogPageForm.parentId=''
        this.dialogPageForm.parentName=''
        this.dialogPageForm.bgColor=''
        this.dialogPageForm.redirect=''
        this.dialogPageForm.pageTitle=''
        this.dialogPageForm.component=''
        this.dialogPageForm.isLogin=''
        this.dialogPageForm.parentList=[]
        this.dialogPageForm.componentList=[]

    },
    //加载组件列表
    async loadComponentList(){
       if(this.dialogPageForm.componentList.length!=0){
         return
       }else{
         this.selectLoading=true
         await getAllComponent().then((data)=>{
           this.dialogPageForm.componentList=data.data.list
           this.selectLoading=false
         })
       }
    },
    //表格显示条数变化触发函数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    //当前页数变化触发函数
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getData();
    },
    //删除按钮，打开删除提示框
    deletePage(index, rows) {
      this.$confirm(
        "此操作将永久删除:" + rows[index].pageName + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          const params = {
            pageId: rows[index].pageId
          };
          await deletePage(params);
          this.getData();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //弹窗关闭按钮事件
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    submitPageForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //判断是否是新增页面
           if(this.isAddPage){
             let params={
               ...this.dialogPageForm,
               loading:true
             }
             //如果pageId不存在，则删除parsms中的pageId属性
             if(params.pageId==''){
               delete params.pageId
             }
             delete params.component
             //isForbid字段，类型转换
              params.isLogin=params.isLogin?1:0
              await addPage(params)
              this.getData()
              this.dialogFormVisible=false
           }else{
              let params={
               ...this.dialogPageForm,
               loading:true
             }
             //isForbid字段，类型转换
              params.isLogin=params.isLogin?1:0
              delete params.component
              await changePage(params).then((data)=>{
              this.getData()
              this.dialogFormVisible=false
              })
           }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.content_body {
  position: relative;
  box-sizing: border-box;
  background: white;
  .pageTitle {
    font-size: 20px;
    font-weight: bold;
    padding: 10px 20px 10px 20px;
    box-shadow: 0px 1px 0px 0px rgba($color: #000000, $alpha: 0.05);
  }
  .page_body {
    padding: 20px;
    .tool {
      margin-bottom: 20px;
    }
    .pagination {
      margin-top: 30px;
    }
  }
}
</style>
<style lang="scss">
@import "@/css/xz.base.scss"
</style>
